package com.tanhua.server.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.server.mapper.*;
import com.tanhua.server.pojo.*;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class SoulService {
    @Autowired
    private QuestionUserLockMapper questionUserLockMapper;

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private SoulQuestionMapper soulQuestionMapper;

    @Autowired
    private SoulQuestionOptionMapper soulQuestionOptionMapper;

    @Autowired
    private QuestionnaireReportMapper questionnaireReportMapper;

    @Autowired
    private QuestionnaireResultMapper questionnaireResultMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;


    public List<QuestionnaireVo> SQuestionnaireLike() {
        //拿到用户id
        User user = UserThreadLocal.get();

        //要返回的vo对象
        List<QuestionnaireVo> questionnaireVoList = new ArrayList<>();
        //通过user_Id找到QuestionUserLock表中的user_id拿到问卷id和锁状态存到问卷vo里面
        LambdaQueryWrapper<QuestionUserLock> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(QuestionUserLock::getUserId, user.getId());
        List<QuestionUserLock> questionUserLock = this.questionUserLockMapper.selectList(queryWrapper1);
        if (CollectionUtils.isEmpty(questionUserLock)) {
            //为用户生成3套题目
            //先随机拿到题目 根据type
            for (int i = 1; i <= 3; i++) {
                QuestionUserLock questionUserLock1 = new QuestionUserLock();
                questionUserLock1.setId(Long.valueOf(i));
                questionUserLock1.setUserId(user.getId());
                questionUserLock1.setQuestionnaireId(Long.valueOf(i));
                questionUserLock1.setIsLock(1);
                if (questionUserLock1.getQuestionnaireId().longValue() == 1) {
                    questionUserLock1.setIsLock(0);
                }
                questionUserLockMapper.insert(questionUserLock1);
                questionUserLock.add(questionUserLock1);
            }
        }

        for (QuestionUserLock userLock : questionUserLock) {
            QuestionnaireVo questionnaireVo = new QuestionnaireVo();
            questionnaireVo.setId(userLock.getQuestionnaireId().toString());
            questionnaireVo.setIsLock(userLock.getIsLock());
            questionnaireVoList.add(questionnaireVo);
        }

        //拿出问卷Id的集合
        List<Long> questionnaireId = new ArrayList();
        for (QuestionUserLock UserId : questionUserLock) {
            questionnaireId.add(UserId.getQuestionnaireId()); // 1 2 3
        }

        //通过拿到的问卷id找到问题表中的数据存在返回问卷vo中
        LambdaQueryWrapper<Questionnaire> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.in(Questionnaire::getId, questionnaireId);
        List<Questionnaire> soulQuestionnaire = this.questionnaireMapper.selectList(queryWrapper2);
        for (Questionnaire questionnaire : soulQuestionnaire) {
            for (QuestionnaireVo questionnaireVo : questionnaireVoList) {
                //把返回vo中的id与从问题表中拿到的id进行对比,确定存放的是同一个vo返回对象
                if (questionnaire.getId().toString().equals(questionnaireVo.getId())) {
                    questionnaireVo.setLevel(questionnaire.getLevel());
                    questionnaireVo.setName(questionnaire.getName());
                    questionnaireVo.setCover(questionnaire.getCover());
                    questionnaireVo.setStar(questionnaire.getStar());
                }
            }
        }

        //把问题vo填充到问卷vo中
        for (QuestionnaireVo questionnaireVo : questionnaireVoList) {

            //拿到试题数据
            //List<SoulQuestionVo> questions;字段中还缺少SoulQuestionVo集合
            //从数据库中拿到SoulQuestionVo信息
            LambdaQueryWrapper<SoulQuestion> queryWrapper3 = new LambdaQueryWrapper<>();
            queryWrapper3.in(SoulQuestion::getQuestionnaireId, questionnaireId);
            List<SoulQuestion> soulQuestions = this.soulQuestionMapper.selectList(queryWrapper3);
            List<SoulQuestionVo> soulQuestionVos = new ArrayList<>();
            //填充SoulQuestionVo的数据
            for (SoulQuestion soulQuestion : soulQuestions) {
                if (questionnaireVo.getId().equals(soulQuestion.getQuestionnaireId().toString())) {
                    SoulQuestionVo soulQuestionVo = new SoulQuestionVo();
                    soulQuestionVo.setId(String.valueOf(soulQuestion.getId()));
                    soulQuestionVo.setQuestion(soulQuestion.getStem());
                    soulQuestionVos.add(soulQuestionVo);
                    //SoulQuestionVo中还有一个List<SoulQuestionOptionVo> options-----选项集合没有填充
                    LambdaQueryWrapper<SoulQuestionOption> queryWrapper4 = new LambdaQueryWrapper<>();
                    queryWrapper4.in(SoulQuestionOption::getQuestionId, soulQuestion.getId());
                    List<SoulQuestionOption> soulQuestionList = this.soulQuestionOptionMapper.selectList(queryWrapper4);
                    List<SoulQuestionOptionVo> soulQuestionOptionVo = new ArrayList<>();
                    //填充soulQuestionOptionVo1数据
                    for (SoulQuestionOption option : soulQuestionList) {
                        SoulQuestionOptionVo soulQuestionOptionVo1 = new SoulQuestionOptionVo();
                        soulQuestionOptionVo1.setId(String.valueOf(option.getId()));
                        soulQuestionOptionVo1.setOption(option.getContent());
                        soulQuestionOptionVo.add(soulQuestionOptionVo1);
                    }
                    //把选项vo集合填充到问题对象中
                    soulQuestionVo.setOptions(soulQuestionOptionVo);
                }
            }
            List<String> stringList = soulQuestionVos.stream().map(SoulQuestionVo::getId).collect(Collectors.toList());
            System.out.println(stringList);
            questionnaireVo.setQuestions(soulQuestionVos);
        }

        return questionnaireVoList;
    }


    public String testSoul(Map<String, List<Answers>> param) {
        List<Answers> answersList = param.get("answers");
        try {
            Integer score = 0;
            Long questionId = 0L;
            //计算分数
            for (Answers answers : answersList) {
                questionId = answers.getQuestionId();
                Long optionId = answers.getOptionId();
                //queryWrapper.eq("question_id", questionId);
                LambdaQueryWrapper<SoulQuestionOption> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SoulQuestionOption::getId, optionId);
                SoulQuestionOption soulQuestionOption = soulQuestionOptionMapper.selectOne(wrapper);
                score += Integer.parseInt(soulQuestionOption.getScore());
            }

            System.out.println(score);

            //通过题目id查到对应的问卷id
            SoulQuestion soulQuestion = soulQuestionMapper.selectById(questionId);
            Long questionnaireId = soulQuestion.getQuestionnaireId();

            //默认初级开启
//        QueryWrapper<QuestionUserLock> queryWrapper = new QueryWrapper();
            LambdaQueryWrapper<QuestionUserLock> wrapper = new LambdaQueryWrapper<>();
            if (questionnaireId <= 2) {
                wrapper.eq(QuestionUserLock::getQuestionnaireId, questionnaireId + 1);
                wrapper.eq(QuestionUserLock::getUserId, UserThreadLocal.get().getId());
                QuestionUserLock questionUserLock = questionUserLockMapper.selectOne(wrapper);
                if (questionUserLock.getIsLock().equals(1)) {
                    questionUserLock.setIsLock(0);
                    questionUserLockMapper.update(questionUserLock, wrapper);
                }


            }
            //根据问卷id,查看结果表，看总分在哪个区间，判断你的性格，并把数据都添加到报告表里
//        QueryWrapper<QuestionnaireResult> query3 = new QueryWrapper<>();
            LambdaQueryWrapper<QuestionnaireResult> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(QuestionnaireResult::getQuestionnaireId, questionnaireId);
            List<QuestionnaireResult> questionnaireResults = questionnaireResultMapper.selectList(wrapper1);
            QuestionnaireReport questionnaireReport = new QuestionnaireReport();
            questionnaireReport.setUserId(UserThreadLocal.get().getId());
            questionnaireReport.setQuestionnaireId(questionnaireId);
            for (QuestionnaireResult questionnaireResult : questionnaireResults) {
                String[] split = questionnaireResult.getScope().split(",");
                if (score >= Integer.valueOf(split[0]) && score <= Integer.valueOf(split[1])) {
                    questionnaireReport.setReportId(questionnaireResult.getId());
                    break;
                }
            }
            questionnaireReportMapper.insert(questionnaireReport);
            return questionnaireReport.getReportId().toString();
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 灵魂测试结果
     *
     * @param id
     * @return
     */
    public TestResultVo testReport(Long id) {
        TestResultVo testResultVo = new TestResultVo();
        List<Dimensions> dimensionList = new ArrayList<>();
        //通过id获取报告里面的数据
        QuestionnaireReport questionnaireReport = questionnaireReportMapper.selectById(id);
        Long resultId = questionnaireReport.getReportId();
        //通过报告表里面的resultId查询数据，写维度集合里
        QuestionnaireResult questionnaireResult = questionnaireResultMapper.selectById(resultId);
        dimensionList.add(new Dimensions("外向", questionnaireResult.getExtroversion()));
        dimensionList.add(new Dimensions("判断", questionnaireResult.getJudgement()));
        dimensionList.add(new Dimensions("抽象", questionnaireResult.getAbstraction()));
        dimensionList.add(new Dimensions("理性", questionnaireResult.getRationality()));

        //保存到testResultVo里面
        testResultVo.setConclusion(questionnaireResult.getContent());
        testResultVo.setCover(questionnaireResult.getCover());
        testResultVo.setDimensions(dimensionList);

        //通过resultId查询报告表，获取所有的用户，存到集合里
        LambdaQueryWrapper<QuestionnaireReport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QuestionnaireReport::getReportId, resultId);
        List<QuestionnaireReport> questionnaireReports = questionnaireReportMapper.selectList(queryWrapper);
        Set<Long> userIds = questionnaireReports.stream().map(QuestionnaireReport::getUserId).collect(Collectors.toSet());

        //查询所有用户的完整信息
        LambdaQueryWrapper<UserInfo> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(UserInfo::getUserId, userIds);
        List<UserInfo> userInfos = userInfoMapper.selectList(queryWrapper1);
        ArrayList<SimilarYou> similarYouList = new ArrayList<>();
        //如果是当前用户就跳过，否则添加到相似的人集合里
        for (UserInfo userInfo : userInfos) {
            if (userInfo.getUserId().longValue() == UserThreadLocal.get().getId().longValue()) {
                // 排除自己
                continue;
            }
            similarYouList.add(new SimilarYou(userInfo.getUserId(), userInfo.getLogo()));
        }

        testResultVo.setSimilarYou(similarYouList);
        return testResultVo;
    }


}
